package com.smit.update.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.smit.update.R;
import com.smit.utils.NetUtil;
import com.smit.utils.SharePrefUtil;

import org.json.JSONException;

import java.io.File;

import static com.smit.utils.SharePrefUtil.SERVER_URL_KEY;
import static com.smit.utils.SharePrefUtil.defaultServerUrl;

public class MainActivity extends BaseActivity {
    final int LOCAL_FILE_SELECT_RQCODE = 1;
    private TextView msgTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        msgTextView = (TextView) findViewById(R.id.msg);
        Button btn1 = (Button) findViewById(R.id.remote_update_button);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断网络是否正常，如果不正常需要进入设置
                if (NetUtil.isNetworkOk(MainActivity.this)
                        && (NetUtil.isEthernetOn(MainActivity.this) || NetUtil.isWifiConnected(MainActivity.this))) {
                    checkUpdate();
                } else {
                    showNetworkErrorDialog();
                }
            }
        });
        Button btn2 = (Button) findViewById(R.id.local_update_button);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开文件管理
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("application/zip|application/x-zip-compressed|multipart/x-zip|application/x-compressed");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, LOCAL_FILE_SELECT_RQCODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == LOCAL_FILE_SELECT_RQCODE) {
            Uri uri = data.getData();
            File file = new File(uri.getPath());
            //只支持zip包文件
            if (file.getAbsolutePath().endsWith(".zip")) {
                updateManager.startOSUpdate(uri.getPath(), true);
            } else {
                Toast.makeText(MainActivity.this, "请选择正确的zip包文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void checkUpdate() {
        final ProgressDialog dialog = new ProgressDialog(MainActivity.this, android.R.style.Theme_Material_Dialog_NoActionBar_MinWidth);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setTitle("获取更新");
        dialog.setMessage("正在从服务器获取更新...");
        RequestCallBack<String> requestCallBack = new RequestCallBack<String>() {
            @Override
            public void onStart() {
                dialog.show();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                JSONObject resultJson = JSON.parseObject(responseInfo.result);
                try {
                    org.json.JSONObject json = new org.json.JSONObject(responseInfo.result);
                    msgTextView.setText("返回结果：\n" + json.toString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (resultJson.getJSONArray("packages").size() > 0) {
                    startUpdateInfoActivity(resultJson);
                } else {
                    msgTextView.setText("您的系统已经是最新.");
                }
                dialog.dismiss();
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                msgTextView.setText(error.getExceptionCode() + ":" + msg);
                dialog.dismiss();
            }
        };

        updateManager.checkUpdate(requestCallBack);
    }

    private void startUpdateInfoActivity(JSONObject jsonObject) {
        Intent intent = new Intent(this, UpdateActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            openSettingsDialog();
            return true;
        }
        if (id == R.id.action_clear_data) {
            String downloadFilePath = SharePrefUtil.getString(this, SharePrefUtil.DOWNLOAD_FILE_PATH,"");
            File file = new File(downloadFilePath);
            if (file.exists()){
                if (!file.delete()){
                    file.deleteOnExit();
                }
            }
            SharePrefUtil.clear(this);
            Toast.makeText(this, R.string.msg_data_has_clear, Toast.LENGTH_LONG).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showNetworkErrorDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Dialog_NoActionBar_MinWidth);
        builder.setTitle("网络错误");
        builder.setMessage("无法连接到网络，请先打开网络连接");
        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.Settings");
                        intent.setComponent(cm);
                        intent.setAction("android.intent.action.VIEW");
                        startActivity(intent);
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

        builder.show();
    }

    private void openSettingsDialog() {
        String serverUrl = SharePrefUtil.getString(this, SERVER_URL_KEY, defaultServerUrl);
        AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_NoActionBar_MinWidth);
        builder.setIcon(null);
        builder.setTitle("服务器的地址：");
        final EditText editText = new EditText(MainActivity.this);
        editText.setTextColor(getResources().getColor(R.color.white));
        editText.setText(serverUrl);
        builder.setView(editText);
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharePrefUtil.saveString(MainActivity.this, SharePrefUtil.SERVER_URL_KEY, editText.getText().toString());
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

        builder.show();
    }
}
